package com.xls.base.aspect;

import com.xls.base.model.SysLog;
import com.xls.base.annotation.Log;
import com.xls.base.mapper.SysLogMapper;
import com.xls.commonutils.IPUtils;
import com.xls.commonutils.JwtUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 系统日志，切面处理类
 *
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private SysLogMapper sysLogMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Pointcut("@annotation(com.xls.base.annotation.Log)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        saveSysLog(point, time);

        return result;
    }

    @Async
    public void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLog sysLog = new SysLog();
        Log log = method.getAnnotation(Log.class);
        if (log != null) {
            //注解上的title-模块
            sysLog.setTitle(log.title());
            //注解上的businessType-功能
            sysLog.setBusinessType(log.businessType());
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        //获取request
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        //请求方式
        sysLog.setRequestMethod(request.getMethod());

        //拿到request中的User-Agent
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));

        //浏览器
        sysLog.setBrowser(userAgent.getBrowser().getName());

        //操作系统
        sysLog.setOs(userAgent.getOperatingSystem().getName());


        //用户名
        //拿到request中的head
        String tokenHeader = "Authorization";
        String authHeader = request.getHeader(tokenHeader);
        // The part after "Bearer "
        String tokenHead = "Bearer";
        String authToken = authHeader.substring(tokenHead.length());
        //解析token获取用户名
        String username = jwtUtils.getUserNameFromToken(authToken);
        sysLog.setUsername(username);

        //请求url
        String url = request.getRequestURI();
        sysLog.setUrl(url);

        //IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));

        //操作时长
        sysLog.setTime(time);

        //保存系统日志
        sysLogMapper.insert(sysLog);
    }

}
